package com.iweb.interceptor;

import cn.hutool.core.util.StrUtil;
import com.iweb.annotation.TokenAuthentication;
import com.iweb.common.jwt.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;


public class TokenInterceptor extends HandlerInterceptorAdapter {

    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        /*改造代码开始*/
        System.out.println("请求url：" + request.getRequestURI());
        // 获取目标方法是否包含 TokenAuthentication 注解,判断是否需要认证
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        if (!method.isAnnotationPresent(TokenAuthentication.class)) {
            // 如果目标方法没有 TokenAuthentication 注解则放行
            return true;
        }
        /*改造代码结束*/
        String token = request.getHeader("token");
        if (StrUtil.isEmpty(token)) {
            throw new RuntimeException("未授权");
        }
        // 解析token
        Claims claims = JwtUtil.parseJWT(token);
        // 验证过期时间
        long time = claims.getExpiration().getTime();
        long now = System.currentTimeMillis();
        if (now > time) {
            throw new RuntimeException("token已过期");
        }
        // 验证身份
        String issuer = claims.getIssuer();
        if (!StrUtil.equals(issuer, "user")) {
            throw new RuntimeException("身份异常");
        }

        // 保存token到request对象
        request.setAttribute("token", token);
        // 保存userId
        request.setAttribute("userId", claims.getId());
        return true;
    }

}
